import cv2

def get_cam_lst(cam_lst=range(0, 24)):
    """探测可用摄像头，返回有效编号列表"""
    arr = []
    for iCam in cam_lst:
        cap = cv2.VideoCapture(iCam)
        if not cap.isOpened():
            cap.release()
            continue
        ret, frame = cap.read()
        if ret:
            arr.append(iCam)
        cap.release()
    return arr

def main():
    print("🔍 正在探测摄像头（0~23）...")
    cams = get_cam_lst()
    
    if not cams:
        print("❌ 未找到任何可用摄像头！")
        return

    print(f"✅ 可用摄像头编号: {cams}")
    
    idx = 0
    current_id = cams[idx]
    cap = cv2.VideoCapture(current_id)
    # 可选：设置分辨率
    cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
    cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)

    print(f"🟢 当前摄像头: #{current_id} | 按 'n' 切换，'q' 退出")

    while True:
        ret, frame = cap.read()
        if not ret:
            print(f"⚠️ 摄像头 #{current_id} 无画面，跳过...")
            break

        # 显示灰度图（更适合红外效果）
        #gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        cv2.imshow('Infrared View - Press n to switch, q to quit', frame)

        key = cv2.waitKey(1) & 0xFF
        if key == ord('q'):
            break
        elif key == ord('n'):
            # 切换到下一个摄像头
            cap.release()
            idx = (idx + 1) % len(cams)
            current_id = cams[idx]
            cap = cv2.VideoCapture(current_id)
            cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
            cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)
            print(f"🔄 已切换到摄像头 #{current_id}")

    cap.release()
    cv2.destroyAllWindows()

if __name__ == "__main__":
    main()